/* 
 *   Classname:  startup.RestErrorEndpoint
 * 
 *   Date       Developer   Description
 *   2018年8月13日    周成功              新建
 *
 */
package SpringBoot.__template.full.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.titan.core.base.BaseController;
import com.titan.core.utils.data.StringUtils;
import com.titan.core.utils.io.ConsoleUtils;
import com.titan.core.web.utils.SpringBootUtils;

/**
 *
 *
 * @author 周成功
 *
 */
@RestController
public class CustomErrorController extends BaseController implements ErrorController {
    private static final String PATH = "/error";
    @Autowired
    private ErrorAttributes errorAttributes;
    
    @RequestMapping(value = PATH)
    public void error(HttpServletRequest request, HttpServletResponse response) throws Exception {
        if(SpringBootUtils.getEnvironmentTitan().isTitanModeDevelopment()) {
            buildBody(request, response, true);
        } else {
            buildBody(request, response, false);
        }
    }

    private void buildBody(HttpServletRequest request, HttpServletResponse response, Boolean includeStackTrace) throws Exception {
        Map<String,Object> errorAttributes = getErrorAttributes(request, includeStackTrace);
        ConsoleUtils.print("错误信息", errorAttributes);
        
        Integer status = (Integer)errorAttributes.get("status");
        String path=(String)errorAttributes.get("path");
        String messageFound=(String)errorAttributes.get("message");
        String message="";
        String trace ="";
        if(!StringUtils.isEmpty(path)){
            message = String.format("Requested path %s with result %s", path, messageFound);
        }
        if(includeStackTrace) {
             trace = (String) errorAttributes.get("trace");
             if(!StringUtils.isEmpty(trace)) {
                 message += String.format(" and trace %s", trace);
             }
        }
        writeJson(response, "status", status, "message", message);
        
//        return FailureResponseBody.builder().code(0).status(status).message(message).build();
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }
    private Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace);
    }
}
